"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Plus,
  Edit,
  Trash2,
  Download,
  ArrowUpDown,
  Eye,
  FileText,
  ImageIcon,
  File,
  Upload,
  ChevronLeft,
  ChevronRight,
} from "lucide-react"

interface DataSource {
  id: string
  name: string
  template: string
  uploader: string
  createTime: string // 改为createTime
  sourceType: "Word" | "PDF" | "图片" | "文本"
  extractPreview: string
  status: "已处理" | "处理中" | "待处理"
}

export default function DataManagement() {
  // 按创建时间倒序排列
  const [dataSources] = useState<DataSource[]>([
    {
      id: "1",
      name: "2024年1月财务数据",
      template: "月度财务报告模板",
      uploader: "张三",
      createTime: "2024-01-15", // 最近的日期
      sourceType: "Word",
      extractPreview: "收入: 1,250,000元, 支出: 980,000元, 净利润: 270,000元...",
      status: "已处理",
    },
    {
      id: "2",
      name: "市场调研问卷结果",
      template: "市场分析报告模板",
      uploader: "李四",
      createTime: "2024-01-12", // 第二近的日期
      sourceType: "PDF",
      extractPreview: "满意度: 85%, 购买意向: 72%, 品牌认知度: 68%...",
      status: "已处理",
    },
    {
      id: "3",
      name: "员工绩效评分表",
      template: "员工绩效评估模板",
      uploader: "王五",
      createTime: "2024-01-10", // 第三近的日期
      sourceType: "图片",
      extractPreview: "平均分: 4.2/5, 优秀率: 35%, 合格率: 92%...",
      status: "处理中",
    },
  ])

  const [selectedItems, setSelectedItems] = useState<string[]>([])
  const [isSourceDialogOpen, setIsSourceDialogOpen] = useState(false)
  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false)
  const [selectedSource, setSelectedSource] = useState<DataSource | null>(null)

  // 分页状态
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage] = useState(10)
  const totalPages = Math.ceil(dataSources.length / itemsPerPage)

  const getSourceIcon = (type: string) => {
    switch (type) {
      case "Word":
        return <FileText className="h-4 w-4" />
      case "PDF":
        return <File className="h-4 w-4" />
      case "图片":
        return <ImageIcon className="h-4 w-4" />
      case "文本":
        return <FileText className="h-4 w-4" />
      default:
        return <File className="h-4 w-4" />
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case "已处理":
        return "bg-green-500"
      case "处理中":
        return "bg-yellow-500"
      case "待处理":
        return "bg-gray-500"
      default:
        return "bg-gray-500"
    }
  }

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedItems(dataSources.map((item) => item.id))
    } else {
      setSelectedItems([])
    }
  }

  const handleSelectItem = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedItems([...selectedItems, id])
    } else {
      setSelectedItems(selectedItems.filter((item) => item !== id))
    }
  }

  const handleViewSource = (dataSource: DataSource) => {
    setSelectedSource(dataSource)
    setIsSourceDialogOpen(true)
  }

  const handleUploadData = () => {
    setIsUploadDialogOpen(true)
  }

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">数据管理</h1>
        <div className="flex gap-2">
          {selectedItems.length > 0 && (
            <>
              <Button variant="outline">
                <Download className="h-4 w-4 mr-2" />
                批量下载
              </Button>
              <Button variant="outline">
                <Trash2 className="h-4 w-4 mr-2" />
                批量删除
              </Button>
            </>
          )}
          <Button onClick={handleUploadData}>
            <Plus className="h-4 w-4 mr-2" />
            上传数据
          </Button>
        </div>
      </div>

      <div className="border rounded-lg">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">
                <Checkbox checked={selectedItems.length === dataSources.length} onCheckedChange={handleSelectAll} />
              </TableHead>
              <TableHead className="cursor-pointer">
                数据名称 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead>关联模板</TableHead>
              <TableHead className="cursor-pointer">
                上传人 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead className="cursor-pointer">
                生成时间 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead>来源数据</TableHead>
              <TableHead>抽取结果预览</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {dataSources.map((dataSource) => (
              <TableRow key={dataSource.id}>
                <TableCell>
                  <Checkbox
                    checked={selectedItems.includes(dataSource.id)}
                    onCheckedChange={(checked) => handleSelectItem(dataSource.id, checked as boolean)}
                  />
                </TableCell>
                <TableCell className="font-medium">{dataSource.name}</TableCell>
                <TableCell>{dataSource.template}</TableCell>
                <TableCell>{dataSource.uploader}</TableCell>
                <TableCell>{dataSource.createTime}</TableCell>
                <TableCell>
                  <Button
                    variant="ghost"
                    className="p-0 h-auto flex items-center gap-2"
                    onClick={() => handleViewSource(dataSource)}
                  >
                    {getSourceIcon(dataSource.sourceType)}
                    <span className="text-sm">{dataSource.sourceType}</span>
                  </Button>
                </TableCell>
                <TableCell className="max-w-xs">
                  <div className="truncate text-sm text-gray-600">{dataSource.extractPreview}</div>
                </TableCell>
                <TableCell>
                  <Badge className={`${getStatusColor(dataSource.status)} text-white`}>{dataSource.status}</Badge>
                </TableCell>
                <TableCell>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm">
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Download className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        {/* 分页器 */}
        <div className="flex items-center justify-center py-4 border-t">
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">
              第 {currentPage} 页，共 {totalPages} 页
            </span>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* 来源数据弹窗 */}
      <Dialog open={isSourceDialogOpen} onOpenChange={setIsSourceDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>来源数据 - {selectedSource?.name}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>数据类型</Label>
              <div className="flex items-center gap-2 mt-1">
                {selectedSource && getSourceIcon(selectedSource.sourceType)}
                <span>{selectedSource?.sourceType}</span>
              </div>
            </div>
            <div>
              <Label>文件预览</Label>
              <div className="border rounded-lg p-4 h-64 bg-muted/30 mt-1 flex items-center justify-center">
                {selectedSource?.sourceType === "Word" && (
                  <div className="text-center">
                    <FileText className="h-16 w-16 mx-auto text-gray-400" />
                    <p className="mt-2">Word文档预览</p>
                  </div>
                )}
                {selectedSource?.sourceType === "PDF" && (
                  <div className="text-center">
                    <File className="h-16 w-16 mx-auto text-gray-400" />
                    <p className="mt-2">PDF文档预览</p>
                  </div>
                )}
                {selectedSource?.sourceType === "图片" && (
                  <div className="text-center">
                    <ImageIcon className="h-16 w-16 mx-auto text-gray-400" />
                    <p className="mt-2">图片预览</p>
                  </div>
                )}
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsSourceDialogOpen(false)}>
                关闭
              </Button>
              <Button>
                <Download className="h-4 w-4 mr-2" />
                下载原始文件
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 上传数据弹窗 */}
      <Dialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>上传数据</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="dataName">数据名称</Label>
              <Input id="dataName" placeholder="请输入数据名称" />
            </div>
            <div>
              <Label htmlFor="dataDesc">数据描述</Label>
              <Textarea id="dataDesc" placeholder="请输入数据描述" />
            </div>
            <div>
              <Label htmlFor="relatedTemplate">关联模板</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="选择关联模板" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="template1">月度财务报告模板</SelectItem>
                  <SelectItem value="template2">市场分析报告模板</SelectItem>
                  <SelectItem value="template3">员工绩效评估模板</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>上传数据源文件</Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                <Upload className="h-8 w-8 mx-auto mb-2 text-gray-400" />
                <p className="text-sm text-gray-600">点击上传或拖拽文件到此处</p>
                <p className="text-xs text-gray-400 mt-1">支持 .docx, .doc, .pdf, .jpg, .png, .txt 格式</p>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsUploadDialogOpen(false)}>
                取消
              </Button>
              <Button>上传</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
